//
//  LicensePlateViewController.m
//  XinKaiFa55like
//
//  Created by junseek on 2017/3/22.
//  Copyright © 2017年 55like lj. All rights reserved.
//

#import "LicensePlateViewController.h"
#import "ProductKeysView.h"
#import "RHTableView.h"
#import "ButtonPullDown.h"
#import "LicensePlateTableViewCell.h"
#import "UILabel+atrribulttext.h"
#import "SelectTypeView.h"
#import "V4TestLicensePlateContentViewController.h"
#import "UserSupplyDemandViewController.h"
#import "UserProjectViewController.h"
#import "CompanyNoticeViewController.h"
//#import "JPUSHService.h"
#import "V4LicensePlateOtherTypeView.h"

@interface LicensePlateViewController ()<ProductKeysViewDelegate,UISearchBarDelegate,SelectTypeViewDelegate,RHTableViewDelegate>{
    UISearchBar *txtSearch;
    ProductKeysView *productKey;
    
    UIView *viewTypeBG;
    ButtonPullDown *btnType1;//行业
    ButtonPullDown *btnType2;//城市
    ButtonPullDown *btnType3;//类型
    ButtonPullDown *btnType5;//其他
    
    NSMutableDictionary *selectDicType;
    
    RHTableView *table_user;
    
    UILabel *lblNum_header;
    
    SelectTypeView *selectType;
    NSString *strSearchKey;
    
    BOOL boolPopRefresh;
    NSInteger tipNum;
    
    V4LicensePlateOtherTypeView *V4TypeView;
    
}

@end

@implementation LicensePlateViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    txtSearch.text=@"";
    //注册监听键盘事件
    RegisterNotify(UIKeyboardWillShowNotification, @selector(handleKeyboardDidShow:))
    RegisterNotify(UIKeyboardWillHideNotification, @selector(handleKeyboardWillHide:))
//    RegisterNotify(@"JPushMessage", @selector(pushMessageData:))
    if (boolPopRefresh) {
        boolPopRefresh=NO;
        [table_user refresh];
    }
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    RemoveNofify
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    selectDicType=[NSMutableDictionary new];
    
    
//    RegisterNotify(@"againLoadUserData", @selector(againLoadUserData))
    [self navbarTitle:@"   "];
    [self rightButton:nil image:@"headsearch" sel:@selector(rightButtonClicked)];
    [self.navrightButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 10)];
    self.backButton.frameWidth=50;
    self.navrightButton.frame=CGRectMake(kScreenWidth-50, 20, 50, 44);
    
    txtSearch= [[UISearchBar alloc] initWithFrame:CGRectMake(50, 20, kScreenWidth-100, 43.5)];
    txtSearch.delegate=self;
    txtSearch.placeholder=@"搜索";
    [self.navView addSubview:txtSearch];
    [txtSearch setBackgroundImage:[[Utility Share] imageFromColor:[UIColor clearColor] rect:txtSearch.frame.size]];
     UITextField *searchField=[txtSearch valueForKey:@"_searchField"];
    searchField.backgroundColor = [UIColor whiteColor];
   
    
    
    viewTypeBG=[[UIView alloc] initWithFrame:CGRectMake(0, kTopHeight, kScreenWidth, 40)];
    viewTypeBG.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:viewTypeBG];
    [self initViewTypeButtons];
    
    table_user=[[RHTableView alloc]initWithFrame:CGRectMake(0, YH(viewTypeBG), kScreenWidth, H(self.view)-YH(viewTypeBG))];
    [table_user showRefresh:YES LoadMore:YES];
    table_user.delegate = self;
    table_user.dataSource = self;
    table_user.delegate2=self;
    [table_user setBackgroundColor:rgbGray];
    [table_user setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.view addSubview:table_user];
    [table_user registerClass:[LicensePlateTableViewCell class] forCellReuseIdentifier:@"LicensePlateTableViewCell"];
    [table_user setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
    
    
    if ([self.userInfo isEqualToString:@"search"]) {
        [self.navrightButton setImage:nil forState:UIControlStateNormal];
        [self.navrightButton setTitle:@"取消" forState:UIControlStateNormal];
        [self againLoadUserData];
    }else{
        txtSearch.hidden=YES;
        [selectDicType setValue:[self.otherInfo valueForJSONStrKey:@"id"] forKey:@"industry"];
        [btnType1 setButtonTitle:[self.otherInfo valueForJSONStrKey:@"name"]];
        [self loadTableData];
        [self loadProductskeywords];
        strSearchKey=[self.otherInfo valueForJSONStrKey:@"name"];
    }
}

//----------------------------------type---------------------------------------
-(void)initViewTypeButtons{
    
    float fw=(kScreenWidth)/4.0;
    //-----------------------------类型-----------------------------
    btnType1=[[ButtonPullDown alloc] initWithFrame:CGRectMake(0, 0, fw, 40) withSel:@selector(sampleTypeButtonClicked:) addTarget:self buttonTitle:@"行业"];
    [viewTypeBG addSubview:btnType1];
    btnType2=[[ButtonPullDown alloc] initWithFrame:CGRectMake(fw, 0, fw, 40) withSel:@selector(sampleTypeButtonClicked:) addTarget:self buttonTitle:@"城市"];
    [viewTypeBG addSubview:btnType2];
    btnType3=[[ButtonPullDown alloc] initWithFrame:CGRectMake(fw*2, 0, fw, 40) withSel:@selector(sampleTypeButtonClicked:) addTarget:self buttonTitle:@"类型"];
    [viewTypeBG addSubview:btnType3];
//    btnType4=[[ButtonPullDown alloc] initWithFrame:CGRectMake(fw*3, 0, fw, 40) withSel:@selector(sampleTypeButtonClicked:) addTarget:self buttonTitle:@""];
//    [viewTypeBG addSubview:btnType4];
    btnType5=[[ButtonPullDown alloc] initWithFrame:CGRectMake(fw*3, 0, fw, 40) withSel:@selector(sampleTypeButtonClicked:) addTarget:self buttonTitle:@"其他"];
    [viewTypeBG addSubview:btnType5];
    
    [viewTypeBG addSubview:[RHMethods lineViewWithFrame:CGRectMake(0, 39.5, kScreenWidth, 0.5)]];
}

#pragma mark selector
-(void)againLoadUserData{
    [selectDicType removeAllObjects];
    [btnType1 setButtonTitle:@"行业"];
    [btnType2 setButtonTitle:@"城市"];
    [btnType3 setButtonTitle:@"类型"];
    [btnType5 setButtonTitle:@"其他"];
    
    [[Utility Share] setIsUserLogin:YES];
    [[Utility Share] hiddenStartTransitionView];
//    [JPUSHService setAlias:[NSString stringWithFormat:@"%@",[[Utility Share] userId]] callbackSelector:nil object:@""];
    
    [self loadTableData];
    [self loadProductskeywords];
    ///处理推送信息
//    if ([[Utility Share] isPushMessage] && [[Utility Share] userPushData]) {
//        [[Utility Share] setIsPushMessage:NO];
//        [self refreshPushUI: [[Utility Share] userPushData]];
//    }
}
-(void)loadTableData{
    krequestParam
    [dictparam setValue:@"%@" forKey:@"page"];
    [dictparam setValue:@"20" forKey:@"pagesize"];
    [dictparam setValue:@"lists" forKey:@"type"];

    [dictparam setValue:[selectDicType valueForJSONStrKey:@"industry"] forKey:@"cid"];
    [dictparam setValue:[selectDicType valueForJSONStrKey:@"level"] forKey:@"level"];
    [dictparam setValue:[selectDicType valueForJSONStrKey:@"type"] forKey:@"typeid"];
    [dictparam setValue:[selectDicType valueForJSONStrKey:@"cityName"] forKey:@"city"];
    
    [dictparam setValue:[selectDicType valueForJSONStrKey:@"order"] forKey:@"order"];
//    if ([[selectDicType valueForJSONStrKey:@"sort"]isEqualToString:@"view"]) {
//        [dictparam setValue:@"desc" forKey:@"viewsort"];
//    }else if ([[selectDicType valueForJSONStrKey:@"sort"]isEqualToString:@"praise"]) {
//        [dictparam setValue:@"desc" forKey:@"praisesort"];
//    }
    
    strSearchKey=txtSearch.text;
    if (!txtSearch.hidden) {
        [dictparam setValue:strSearchKey forKey:@"keys"];
    }
    
    table_user.urlString=[NSString stringWithFormat:@"%@%@",XKFV4productslists,dictparam.wgetParamStr];
    [table_user refresh];
}
-(void)loadProductskeywords{
    [NetEngine createGetAction_LJ_two:[NSString stringWithFormat:XKFproductskeywords,[[Utility Share] userId],[[Utility Share] userToken],@""] onCompletion:^(id resData, BOOL isCache) {
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
            [[Utility Share] setArrayProductKeys:[[resData objectForJSONKey:@"data"] objectForJSONKey:@"list"]];
        }else{
            [self loadProductskeywords];
        }
    } onError:^(NSError *error) {
        [self loadProductskeywords];
    }];
}
-(void)rightButtonClicked{
    if (txtSearch.hidden) {
        txtSearch.hidden=NO;
        [self.navrightButton setImage:nil forState:UIControlStateNormal];
        [self.navrightButton setTitle:@"取消" forState:UIControlStateNormal];
    }else{
        txtSearch.hidden=YES;
        [self.navrightButton setImage:[UIImage imageNamed:@"headsearch"] forState:UIControlStateNormal];
        [self.navrightButton setTitle:nil forState:UIControlStateNormal];
    }
}
#pragma mark RHTableViewDelegate
-(void)refreshData:(RHTableView *)view{
    if (view.dataDic) {
        tipNum=[[view.dataDic valueForJSONStrKey:@"unreadnum"] integerValue];
        //tipNum
        [self refreshTabBarTipData];
//        lblNum_header.text=[NSString stringWithFormat:@"当前：%@ 数据",[view.dataDic valueForJSONStrKey:@"total"]];
//        [lblNum_header setColor:rgbpublicColor contenttext:[view.dataDic valueForJSONStrKey:@"total"]];
    }
}
-(void)refreshTabBarTipData{
    UILabel *lblTip=[[[[Utility Share] CustomTabBar_zk] tabBar] viewWithTag:200];
    if (tipNum>0) {
        lblTip.hidden=NO;
        if (tipNum>99) {
            lblTip.text=@"99+";
        }else{
            lblTip.text=[NSString stringWithFormat:@"%ld",tipNum];
        }
        float fw=[lblTip sizeThatFits:CGSizeMake(MAXFLOAT, H(lblTip))].width+8;
        fw=fw<H(lblTip)?H(lblTip):fw;
        lblTip.frameWidth=fw;
    }else{
        lblTip.hidden=YES;
    }
}
#pragma mark Keyboard
-(void)handleKeyboardDidShow:(NSNotification *)notification{
    
    NSDictionary *info = [notification userInfo];
    CGRect keyboardFrame;
    [[info objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardFrame];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue].size;
    CGFloat distanceToMove = kbSize.height;
    NSLog(@"---->动态键盘高度:%f",distanceToMove);
    if (!productKey) {
        productKey=[[ProductKeysView alloc] init];
        [self.view addSubview:productKey];
        productKey.delegate=self;
    }
    productKey.frame=CGRectMake(0, kTopHeight+40, kScreenWidth, kScreenHeight-distanceToMove-kTopHeight-40);
    [productKey showAllArray:[[Utility Share] arrayProductKeys]];
    
    [UIView animateWithDuration:0.3 animations:^{
        
    } completion:^(BOOL finished) {
        
    }];
}
- (void)handleKeyboardWillHide:(NSNotification *)notification
{
    [productKey hidden];
    [UIView animateWithDuration:0.3 animations:^{
        
    }completion:^(BOOL finished) {
        
    }];
}
#pragma mark button
-(void)sampleTypeButtonClicked:(ButtonPullDown *)btn{
    [self.view endEditing:YES];
    if (btn==btnType5){
        //其他类型
        if (!V4TypeView) {
            V4TypeView=[[V4LicensePlateOtherTypeView alloc] init];
        }
        __weak LicensePlateViewController *weakC=self;
        [V4TypeView show:^(NSInteger suc, NSDictionary *dic) {
            if (suc==1) {
                //排序
                [selectDicType setValue:[dic valueForJSONStrKey:@"id"] forKey:@"order"];
                [weakC loadTableData];
            }else if (suc==2){
                //等级                
                [selectDicType setValue:[dic valueForJSONStrKey:@"id"] forKey:@"level"];
                [weakC loadTableData];
            }
        }];
        return;
    }
    if (!selectType) {
        selectType=[[SelectTypeView alloc] init];
        selectType.delegate=self;
    }
    selectType.floatTypeY=Y(table_user);
    btn.selected=YES;
    NSString *strType;
    NSMutableArray *arrayType=[NSMutableArray new];
    if (btn==btnType1) {
        strType=@"industry";
        [arrayType addObject:@{@"name":@"所有行业"}];
        [arrayType addObjectsFromArray:[[[Utility Share] userTypeData] objectForJSONKey:@"cate"]];
    }else if (btn==btnType2){
        strType=@"city";
        [arrayType addObject:@{@"name":@"所有城市"}];
        [arrayType addObjectsFromArray:[[[Utility Share] userTypeData] objectForJSONKey:@"city"]];
    }else if (btn==btnType3){
        strType=@"type";//Grade
        [arrayType addObject:@{@"name":@"所有类型"}];
        [arrayType addObjectsFromArray:[[[Utility Share] userTypeData] objectForJSONKey:@"types"]];//level
//    }else if (btn==btnType4){
//        strType=@"type";
//        [arrayType addObject:@{@"name":@"所有类型"}];
//        [arrayType addObjectsFromArray:[[[Utility Share] userInfo] objectForJSONKey:@"types"]];
//    }else if (btn==btnType5){
//        strType=@"sort";
//        [arrayType addObject:@{@"name":@"默认排序"}];
//        [arrayType addObject:@{@"name":@"浏览量排序",@"id":@"view"}];
//        [arrayType addObject:@{@"name":@"点赞排序",@"id":@"praise"}];
    }
    selectType.strType=strType;
    [selectType showAllArray:arrayType selectDic:@{@"id":[selectDicType valueForJSONStrKey:strType]}];
}
#pragma mark SelectTypeViewDelegate
-(void)selectTypeView:(SelectTypeView *)sview object:(NSDictionary *)dic{
    [selectDicType setValue:[dic valueForJSONStrKey:@"id"] forKey:sview.strType];
    if ([sview.strType isEqualToString:@"industry"]) {
        [btnType1 setButtonTitle:[dic valueForJSONStrKey:@"name"]];
        btnType1.selected=NO;
    }else if ([sview.strType isEqualToString:@"city"]){
        [btnType2 setButtonTitle:[dic valueForJSONStrKey:@"name"]];
        if ([[dic valueForJSONStrKey:@"id"] notEmptyOrNull]) {
            [selectDicType setValue:[dic valueForJSONStrKey:@"name"] forKey:@"cityName"];
        }else{
            [selectDicType setValue:@"" forKey:@"cityName"];
        }
        
        btnType2.selected=NO;
    }else if ([sview.strType isEqualToString:@"type"]){//Grade
        [btnType3 setButtonTitle:[dic valueForJSONStrKey:@"name"]];
        btnType3.selected=NO;
//    }else if ([sview.strType isEqualToString:@"type"]){
//        [btnType4 setButtonTitle:[dic valueForJSONStrKey:@"name"]];
//        btnType4.selected=NO;
//    }else if ([sview.strType isEqualToString:@"sort"]){
//        [btnType5 setButtonTitle:[dic valueForJSONStrKey:@"name"]];
//        btnType5.selected=NO;
    }
    [self loadTableData];
}
-(void)selectTypeViewHidden:(SelectTypeView *)sview{
    btnType1.selected=NO;
    btnType2.selected=NO;
    btnType3.selected=NO;
//    btnType4.selected=NO;
    btnType5.selected=NO;
}
#pragma mark - tableView
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [table_user.dataArray  count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic=[table_user.dataArray objectAtIndex:indexPath.row];
    float fth=[self heightForLabel:kScreenWidth-50 font:fontTitle text:[dic valueForJSONStrKey:@"stitle"]];
    fth = fth>20?40:20;
    return fth+65;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic=[table_user.dataArray objectAtIndex:indexPath.row];
    LicensePlateTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"LicensePlateTableViewCell" forIndexPath:indexPath];
    [cell setValueForDictionary:dic indexPath:indexPath type:@"home" searchKey:strSearchKey];
    return cell;
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.view endEditing:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSMutableDictionary *dic=[[NSMutableDictionary alloc] initWithDictionary:[table_user.dataArray objectAtIndex:indexPath.row]];
    [self pushController:[V4TestLicensePlateContentViewController class] withInfo:@"Insurance" withTitle:@"牌照详情" withOther:dic];
    if ([[dic valueForJSONStrKey:@"isread"] isEqualToString:@"0"]) {
        [dic setValue:@"1" forKey:@"isread"];
        [table_user.dataArray replaceObjectAtIndex:indexPath.row withObject:dic];
        [table_user reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        tipNum--;
        [self refreshTabBarTipData];
    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *viewBG=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 30)];
    viewBG.backgroundColor=rgbGray;
    lblNum_header=[RHMethods labelWithFrame:CGRectMake(10, 7, kScreenWidth, 20) font:fontSmallTitle color:rgbTxtGray text:[NSString stringWithFormat:@"当前：%@ 数据",[table_user.dataDic valueForJSONStrKey:@"total"]]];
    [lblNum_header setColor:rgbpublicColor contenttext:[table_user.dataDic valueForJSONStrKey:@"total"]];
    [viewBG addSubview:lblNum_header];
    return viewBG;
}

#pragma mark UISearchBarDelegate
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
//    [self loadTableData];
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self loadTableData];
    [searchBar resignFirstResponder];
}
#pragma mark ProductKeysViewDelegate
-(void)productKeysView:(ProductKeysView *)selectView clickeDic:(NSDictionary *)dic{
    [txtSearch resignFirstResponder];
    txtSearch.text=[dic valueForJSONStrKey:@"txt"];
    [self loadTableData];
}

#pragma mark popRefresh
-(void)popRefreshData{
    boolPopRefresh=YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
